<template>
  <div>
    <!--  添加图书-->
    <div id="form">
      <el-form label-width="280px" :model="formData">
        <el-form-item label="图书名称">
          <el-input v-model="formData.name" placeholder="请输入图书名称" style="width:100% "></el-input>
        </el-form-item>
        <el-form-item label="图书作者">
          <el-input v-model="formData.author" placeholder="请输入图书作者" style="width:100% "></el-input>
        </el-form-item>
        <el-form-item label="图书价格">
          <el-input type="number" v-model="formData.price" placeholder="请输入图书价格(元)" style="width:100% "></el-input>
        </el-form-item>
        <el-form-item label="出版日期">
          <el-date-picker v-model="formData.release_date" value-format="yyyy-MM-dd" style="width: 100%;" type="date"
                          placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="图书封面">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            list-type="picture-card"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            name="pic">
            <img fit="fill" v-if="formData.pic_path" style="width: 146px;height: 146px" :src="formData.pic_path" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item style="margin-top: 50px;">
          <el-button style="margin-right: 30px" type="primary" @click="onSubmit">立即添加</el-button>
          <el-button type="info" @click="onClean">重新输入</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import bookApi from "@/api/book";
import qs from "qs";
export default {
  name: "add",
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + '/book/uploadPic',
      formData: {
        name: '',
        author: '',
        price: '',
        release_date: '',
        pic_path: '',
      },

    }
  },
  methods: {
    //点击添加
    onSubmit() {
      bookApi.addBook(qs.stringify(this.formData)).then(resp => {
        if (resp.code === 6666) {
          this.$message.success('添加图书成功');
          this.onClean();
          this.$router.push('/book/list')
        } else {
          this.$message.warning('添加图书失败')
        }
      }).catch(() => {
        this.$message.error('添加图书出错')
      })
    },
    //图片上传成功回调函数
    handleAvatarSuccess(response, file, fileList) {
      if (response.code === 6666) {
        this.formData.pic_path = process.env.VUE_APP_BASE_API + '/images/' + response.data.picPath
      }
    },
    //清楚已写的数据
    onClean() {
      this.formData = {};
    }
  }
}
</script>

<style scoped>
#form{
  margin-top: 80px;
  width: 800px;
}
</style>
